package com.mtech.aircdx;

import com.mtech.modbus_rtu.codec.impl.ModbusRTUCodec;
import com.mtech.modbus_rtu.data._03.MultiReadRxDataGram;
import com.mtech.modbus_rtu.data._03.MultiReadTxDataGram;

/**
 * 读取空调状态
 * 
 * @author lixiaolong
 * @CreateDate 2018年3月20日
 */
public class AirCdxReader {
	ModbusRTUCodec codec;
	int addr;

	private AirCdxReader(int addr) {
		this.addr = addr;
		this.codec = ModbusRTUCodec.getInstance();
	}

	/**
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @param addr
	 *            设备地址
	 * @return
	 */
	public static AirCdxReader getInstance(int addr) {
		return new AirCdxReader(addr);
	}

	/**
	 * 查询所有寄存器状态<br>
	 * <b><font color='red'>这会导致通讯时间极大延长,对于串行指令来说影响很大</font></b>
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @return
	 */
	public byte[] readAll() {
		MultiReadTxDataGram tx = new MultiReadTxDataGram(this.addr, AirCdxRegAddr.DOOR_CARD_STATE,
				AirCdxRegAddr.FOUR_TUBES - AirCdxRegAddr.DOOR_CARD_STATE + 1);
		return codec.encode(tx);
	}

	/**
	 * 查询单个寄存器状态
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @param registerAddr
	 *            寄存器地址
	 * @return
	 */
	public byte[] readRegister(byte registerAddr) {
		MultiReadTxDataGram tx = new MultiReadTxDataGram(this.addr, registerAddr, 1);
		return codec.encode(tx);
	}

	/**
	 * 查询连续几个寄存器状态
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @param registerAddr
	 *            起始寄存器地址
	 * @param length
	 *            连续读的寄存器个数
	 * @return
	 */
	public byte[] readRegister(byte registerAddr, int length) {
		MultiReadTxDataGram tx = new MultiReadTxDataGram(this.addr, registerAddr, length);
		return codec.encode(tx);
	}

	/**
	 * 获取设备返回的寄存器状态
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @param buf
	 *            设备回传的字节流
	 * @return
	 */
	public int[] readRegister(byte[] buf) {
		MultiReadRxDataGram rx = new MultiReadRxDataGram(buf);
		return rx.getRegDatas();
	}

}
